<template>
  <div class="pageStyle mg-10 pd-20">
    <div class="searchTable">
      <ElRow class="search-color">
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <span class="search-text">航线名称：</span>
          <ElInput
            v-model="airlineName"
            style="width: 70%"
            placeholder="请输入航线名称"
            @input="spaceInput"
          />
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <ElButton class="b-r-4" type="primary" @click="search()"
            >查询</ElButton
          >
          <ElButton class="b-r-4" @click="resetForm()">重置</ElButton>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="8" :lg="12" :xl="16" class="t-r">
          <ElButton class="b-r-4" type="primary" @click="addClick"
            >添加</ElButton
          >
        </ElCol>
      </ElRow>
    </div>
    <div
      class="tablePage"
      v-loading="showloading"
      element-loading-text="加载中,请稍后..."
    >
      <div style="padding-top: 20px">
        <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
          <ElTable.TableColumn
            prop="airlineName"
            label="航线名称"
            align="center"
          />
          <ElTable.TableColumn prop="airlineType" label="类型" align="center" />
          <!-- <ElTable.TableColumn prop="userName" label="创建人" align="center" /> -->
          <ElTable.TableColumn
            prop="modelName"
            label="无人机型号"
            align="center"
          />
          <ElTable.TableColumn prop="pointNum" label="航点数" align="center">
            <template #default="scope">
              <span>{{ formatPointNum(scope.row.pointNum) }}</span>
            </template>
          </ElTable.TableColumn>
          <ElTable.TableColumn
            prop="totalDistance"
            label="总里程（m）"
            align="center"
          />
          <ElTable.TableColumn
            prop="executeTime"
            label="预计执行时间"
            align="center"
          >
            <template #default="scope">
              <span>{{ formatExecuteTime(scope.row.executeTime) }}</span>
            </template>
          </ElTable.TableColumn>
          <ElTable.TableColumn
            prop="createTime"
            label="创建时间"
            align="center"
          />
          <ElTable.TableColumn fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editClick(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="dowloadTask(scope.row)"
                :disabled="
                  !scope.row.pointNum ||
                  scope.row.pointNum === 0 ||
                  scope.row.executeTime == 'null' ||
                  scope.row.executeTime == '0min0s'
                "
              >
                <ElTooltip
                  :content="
                    !scope.row.pointNum ||
                    scope.row.pointNum === 0 ||
                    scope.row.executeTime == 'null' ||
                    scope.row.executeTime == '0min0s'
                      ? '航线文件无效'
                      : ''
                  "
                  :disabled="scope.row.pointNum && scope.row.pointNum > 0"
                  placement="top"
                >
                  <span>导出</span>
                </ElTooltip>
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="delClick(scope.row)"
                >删除</el-button
              >
            </template>
          </ElTable.TableColumn>
        </ElTable>
      </div>
      <div class="pagination">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 80, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <addroute ref="dialogVisible"></addroute>
  </div>
</template>
<script lang="ts" setup>
import {
  ElButton,
  ElInput,
  ElTable,
  ElPagination,
  ElMessageBox,
  ElRow,
  ElCol,
  ElMessage,
  ElTooltip,
} from "element-plus";
import { ref, onMounted } from "vue";
import { router } from "#/router";
import addroute from "./addroute.vue";
import { list, deleteAirline } from "#/api/task/airline";
const airlineName = ref("");
const tableData = ref([]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
const showloading = ref(false);
const dialogVisible = ref();

const spaceInput = (value: string) => {
  // 过滤空格
  airlineName.value = value.replace(/\s+/g, "");
};

// 格式化航点数显示
const formatPointNum = (pointNum: number) => {
  // 航点数为0或不存在时显示"--"
  if (!pointNum || pointNum === 0) {
    return null;
  }
  return pointNum;
};

// 格式化预计执行时间显示
const formatExecuteTime = (executeTime: string) => {
  // 时间为"0min0s"或不存在时显示"--"
  if (!executeTime || executeTime === "0min0s") {
    return null;
  }
  return executeTime;
};

const search = async () => {
  showloading.value = true;
  const params = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    airlineName: airlineName.value,
  };
  const { data } = await list(params);
  if (data.records.length > 0) {
    tableData.value = data.records;
    total.value = data.total;
  } else {
    tableData.value = [];
    total.value = 0;
  }
  showloading.value = false;
};

const resetForm = () => {
  airlineName.value = "";
  currentPage.value = 1;
  search();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};

const dowloadTask = (row) => {
  // 打开新窗口并下载文件
  window.open(row.airlineUrl, "_blank");
};
const addClick = () => {
  dialogVisible.value.addDialog();
};

const editClick = (row) => {
  let name = row.airlineType == "点状航线" ? "RouteDetail" : "RouteDetailFace";
  router.push({
    name: name,
    query: {
      id: row.id,
      airlineCode: row.airlineCode,
      airlineType: row.airlineType == "点状航线" ? "0" : "1",
      airlineName: row.airlineName,
      // brandId: row.brandId,
      // seriesId: row.seriesId,
      // modelId: row.modelId,
    },
  });

  // dialogVisible.value.editDialog(row);
};

const delClick = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除航线【${row.airlineName}】吗？`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              await deleteAirline(row.id);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
      console.error("删除航线失败:", error);
    }
  }
};

onMounted(() => {
  search();
});
</script>

<style lang="css" scoped>
.pageStyle {
  background: #fff;
}

.tablePage {
  height: calc(100vh - 180px);
}

.el-table--fit {
  height: calc(100vh - 252px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 20px 0 20px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.marginRight {
  margin-right: 10px;
}

.pd-20 {
  padding-bottom: 0px;
}
</style>
